/**
 * @ author: 汪孟苹
 */
define(["jquery","bbcare","comm/datatable/datatable","bch/app/patientManager/lossFollowupUser.ui"],function($,$bb,$datatable,$ui){
    var servers = {};

    var URL = $bb.baseUrl("followapp");
    
    /* 请求队列queue */
    servers.ajaxQueue = function(callback){
        $bb.ajax({
            url: URL + "ctrl/projectManage/qryProjectQueue",
            success: function(data){
                if(data.success){
                    callback(data.data);
                }else{
                    $bb.toastShow(data.msg ? data.msg : "请求队列出错！");
                }
            }
        });
    }
    /**
     * 失访原因
     */
    var ajaxLossReason = function(callback,className,data1){
        $bb.ajax({
            url: URL + "ctrl/processManage/qryLostReasonList",
            success: function (data) {
                if(data.success){
                    callback(data.data,className,data1);
                }else{
                    $bb.toastShow("查询失访原因出错！");
                }
            }
        });
    }
    /**
     * 请求失访原因成功后的回调函数
     */
    var ajaxLossReasonCallBack = function(data,className,data1){
        $ui.reason({ 
            "list": data.rows,
            "dom": $("." + className + " .modal-body"),
        });
        $("." + className).modal('show');
        $(".loss-reason-group .item").unbind("click");
        $(".loss-reason-group .item").click(function(){
            var doctorName = JSON.parse($bb.getSessionStorage("account")).alias;
            var reasonId = $(this).attr("id");
            var channelId = $bb.getChannelId();
            var params = {
                "lostInfo": {
                    "queueId": data1.queueId,
                    "userId": data1.userId,
                    "ptLostNodeId": data1.ptLostNodeId,
                    "reasonId": reasonId
                },
                "oprInfo": {
                    "opCode": "1013",
                    "opNote": "【"+doctorName +"】医生修改了【" + data1.userName + "】患者的失访原因",
                    "opType": "2",
                    "channelType":"2",
                    "channelId":channelId,
                }
            };
            lossReasonSave(params,$datatable.table,className);
        });
    }
    /**
     * 登记失访原因
     */
    var lossReasonSave = function(params,table,className){
        $bb.ajax({
            url: URL + "ctrl/processManage/submitUserLostNodeReason",
            data: JSON.stringify({
                data: params        
            }),
            success: function (data) {
                if(data.success){
                    $("." + className).modal('hide');
                    // 出发dt的重新加载数据的方法
                    table.api().draw(false);
                }else{
                    $bb.toastShow(data.msg ? data.msg : "标记失访原因出错！");
                }
            }
        });
    };

    /******************** 以下是datatable ********************/

    /**
     * 入参
     */
    var inParams = function(args){
        var params = $bb.getPageParams();
        var ageFrom, ageTo;
        if($("#ageFrom-year").val() !="" || $("#ageFrom-month").val() !=""){
            ageFrom = parseInt($("#ageFrom-year").val()*12) + parseInt($("#ageFrom-month").val()*1);
        }else{
            ageFrom = "";
        }
        if($("#ageTo-year").val() !="" || $("#ageTo-month").val() !=""){
            ageTo = parseInt($("#ageTo-year").val()*12) + parseInt($("#ageTo-month").val()*1);
        }else{
            ageTo = "";
        }
        var data = JSON.stringify({
            data: {
                "args": JSON.stringify(args),
                "busiTypeList":params.busiTypeList,
                "hisNo": $.trim($("#hisNo").val()),
                "userName": $.trim($("#userName").val()),
                "phoneNo": $.trim($("#phoneNo").val()),
                "queueId": $("#queue").val(),
                "ageFrom": ageFrom,
                "ageTo": ageTo,
                "beginDate": $("#timeFrom").val(),
                "endDate": $("#timeTo").val(),
            }
        });
        return data;
    }
    /**
     * 出参
     */
    var outParams = function(data){
        return data.rows;
    }
    /**
     * columns
     */
    var columnsHisNo = function(e){
        return e.hisNo ? e.hisNo : e.hisNo1 ? e.hisNo1 : e.hisNo2 ? e.hisNo2 : "-";
    }
    var columnsGender = function(e){
        return e.gender == 'F' ? '女' : '男';
    }
    var columnsData = function(){
        var columnsArr = [
            {"data":columnsHisNo},
            {"data":'userName'},
            {"data":columnsGender},
            {"data":'phoneNo'},
            {"data":'endTime'},
            {"data":'taskName'},
            {"data":'age'},
            {"data":'pregnancyWeek'},
            {"data":'queueName'},
            {
                "data": null,
                "className":"loss-progress"
            },
            {
                "data": null,
                "className":"loss-reason"
            }
        ];
        return columnsArr;
    }
    /**
     * 行绘制回调函数
     */
    var rowCallback = function(row, data, index) {
        // 进度
        var h1 = "";
        var len = data.nodeStatusArr.length;
        var width = parseInt(100 / len) + '%';
        for (var i = 0; i < len; i++) {
            var status = data.nodeStatusArr[i];
            var obj = {};
            if( status == '0' ){                   // 未开始
                obj.className = "progress-notstart";
                obj.title = "未开始";
            }else if( status == '1' ){             // 已完成
                obj.className = "progress-finish";
                obj.title = "已完成";
            }else if( status == '2' ){             // 过期（未开始）
                obj.className = "progress-overdue";
                obj.title = "过期";
            }else if( status == '3' ){             // 过期（补填）
                obj.className = "progress-fill";
                obj.title = "补填";
            }else if( status == '4' ){             // 未完成（部分任务填写）
                obj.className = "progress-nofinish";
                obj.title = "未完成";
            }
            h1 += '<div style="width:'+width+'"><i class="'+obj.className+'" data-toggle="tooltip" data-placement="top" title="'+obj.title+'"></i></div>';
        }
        var html = '<div class="progress-wrap">'+ h1 +'</div>';
        $('td.loss-progress', row).html(html);
        // 失访原因
        var h2 = !data.reasonName || data.reasonName == "" ? '<div class="operate-box"><i class="fa fa-wpforms color-blue" data-toggle="tooltip" data-placement="top" title="登记"></i></div>' : data.reasonName;
        $('td.loss-reason', row).html(h2);
        $("td.loss-reason .color-blue",row).unbind("click");
        $("td.loss-reason .color-blue",row).click(function(){
            var className = "lossModal";
            $bb.modal({
                "className": className,
                "tit": "失访原因",
            },function(){
                ajaxLossReason(ajaxLossReasonCallBack,className,data);
            });
        });
    };
    /**
     * 初始化完成之后的回调函数
     */
    var initComplete = function(setting,json){
        var id = $(".layout-bottom table").attr("id");
        $("#" + id).prev("div.row").remove();
        // 搜索 
        $("#serchBtn").click(function(){
            $datatable.table.api().ajax.reload();  // 出发dt的重新加载数据的方法
            var args = $datatable.table.api().ajax.params();   //获取dt请求参数 
        });
        // 初始化所有工具提示
        $(function(){$("[data-toggle='tooltip']").tooltip();});
    }
    /**
     * 获取datatable里的options
     */
    servers.getOptions = function(){
        var sessionId = $bb.getSessionStorage("sessionId");
        var options = {
            "ajax": {
                "url": URL + "ctrl/ptmanage/qryLostUserList?sessionId=" + sessionId,
                "data": inParams,
                "dataSrc": outParams
            },
            "columns": columnsData(),
            "rowCallback": rowCallback,
            "initComplete": initComplete,
        };
        return options;
    }

    return servers;
});